package me.shurufa.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.adapter.NoticeMessageAdapter;
import me.shurufa.bean.Notice;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.NoticeListResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;

/**
 * 作者 : andy
 * 日期 : 16/3/13 21:22
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 消息通知界面 Fragment
 */
public class MessageCenterFragment extends BaseFragment {

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    private NoticeMessageAdapter mAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter;
    private List<Notice> mDataList;
    private int mPage = 1;
    private boolean hasMore = true;

    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
            reqGetMessageList(mPage);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message_center, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        setRefresh();
        mDataList = new ArrayList();
        mAdapter = new NoticeMessageAdapter(getActivity(), mDataList);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.getRecyclerView().addOnScrollListener(mOnScrollListener);

        if (recyclerView.getEmptyView() != null) {
            View v = recyclerView.getEmptyView();
            TextView empty_text = (TextView) v.findViewById(R.id.empty_text);
            empty_text.setText("暂无消息提示");
        }
    }

    @Override
    public void refresh() {
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        }, 1000);
        mPage = 1;
        RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
        reqGetMessageList(mPage);
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView() , Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    reqGetMessageList(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView() , Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, ((SuperRecyclerView) view).getRecyclerView() , view1);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }


    /**
     * 请求消息列表
     */
    private void reqGetMessageList(final int page) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("page", page);
        HttpRequest.post(API.GET_NOTICE_LIST, params, new HttpCallback<NoticeListResp>() {
            @Override
            public void onRespSuccess(NoticeListResp noticeListResp) {
                try {
                    handleResponse(noticeListResp, (page == 0 || page == 1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(NoticeListResp noticeListResp) {

            }

            @Override
            public void onStart() {
                super.onStart();
                if (NetworkUtils.isNetAvailable(getActivity())) {
                    RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
                } else {
                    // 是上拉加载
                    if (mPage > 1) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                refreshComplete();
            }
        });
    }

    /**
     * 处理返回结果
     * 1. 去重
     * @param listResp     data
     * @param isPullToRefresh  boolean
     */
    private void handleResponse(NoticeListResp listResp, boolean isPullToRefresh) {
        // 是否还有更多
        hasMore = !(listResp.data == null || Utils.isNullForList(listResp.data));

        // 1. 判空
        if (listResp.data == null || Utils.isNullForList(listResp.data)) {
            if (isPullToRefresh) {
                recyclerView.getEmptyView().setVisibility(View.VISIBLE);
            }
            return;
        }

        // 2. 去重
        if (!isPullToRefresh) {
        } else {
            mAdapter.clear();
            mAdapter.notifyDataSetChanged();
        }

        // 3. 添加进列表并刷新
        mAdapter.append(listResp.data);
        mPage ++;

    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            if (recyclerView.getRecyclerView() == null) {
                return;
            }
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }

        // 是下拉加载
        if (ptrRefresh != null && mPage <= 1) {
            ptrRefresh.refreshComplete();
        }
    }


}
